<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="600px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #starter_param="{ model, field }">
        <TreeSelect
          :field-names="{ label: 'name', value: 'code' }"
          v-model:value="model[field]"
          show-search
          allow-clear
          multiple
          tree-default-expand-all
          :tree-data="userDeptOptions"
          tree-node-filter-prop="name"
          @change="handleStarterParamShow"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, getDepartmentData } from './setupProxy.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { getUserProxyCreate, getUserProxyUpdate } from '/@/api/flowManage/flowManage';
  import { TreeSelect } from 'ant-design-vue';
  import { dateUtil as dayjs } from '/@/utils/dateUtil';
  import { isArray } from '/@/utils/is';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'MobileApplistConfigListDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      TreeSelect,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const userStore = useUserStore();
      const userInfo = userStore.getUserInfo;
      const isUpdate = ref(true);
      let dataRef = ref<Recordable>({});

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          dataRef.value = data.record;
          dataRef.value.flow_code = data.record.flowCode;
          dataRef.value.userRealNames = data.record.personRealNameRelated;
          dataRef.value.users = data.record.personRelated;

          dataRef.value.dates = [dataRef.value.beginDate, dataRef.value.endDate];
          if (dataRef.value.deptNames) {
            dataRef.value.starter_param = data.record.deptCodes.split(',');
          }
          setFieldsValue({
            ...dataRef.value,
          });
        } else {
          dataRef.value = {};
        }
      });
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          let formData = Object.assign({}, dataRef.value, values);
          if (formData.starter_param && formData.starter_param.length) {
            formData.starter_param = formData.starter_param.join(',');
          } else {
            formData.starter_param = '';
          }
          if (isArray(formData.dates) && formData.dates.length) {
            formData.proxyBeginDate = dayjs(formData.dates[0]).format('YYYY-MM-DD HH:mm:ss');
            formData.proxyEndDate = dayjs(formData.dates[1]).format('YYYY-MM-DD HH:mm:ss');
          }
          Reflect.deleteProperty(formData, 'dates');
          console.log('formData', formData);
          setDrawerProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            formData.userName = userInfo.name;
            await getUserProxyCreate(formData);
          } else {
            await getUserProxyUpdate(formData);
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      const userDeptOptions = ref([]);
      const getDepartmentDataList = async () => {
        try {
          userDeptOptions.value = (await getDepartmentData()) || [];
        } catch (err) {
          console.log(err);
        }
      };
      const fetch = () => {
        getDepartmentDataList();
      };
      onMounted(fetch);

      const handleStarterParamShow = () => {};

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        dataRef,
        userDeptOptions,
        handleStarterParamShow,
      };
    },
  });
</script>
